﻿using Lin_shop.Models;
using Lin_shop.Models.Database;
using Lin_shop.Models.Shop;
using Lin_shop.Services;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using WebAPI_Demo;

namespace Lin_shop.Controllers
{
    //api/Shop/方法名字
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class CommonalityController : ControllerBase
    {
        //定义数据库上下文
        private readonly ShopContext _db;
        //定义服务类
        private readonly IDataServices _dataService;
        /// <summary>
        // 定义单例服务
        /// </summary>
        private readonly ISingletonServices _singletonServices;
        private readonly ITransientService _transientService;
        private readonly IScopedService _scopedService;

        /// <summary>
        /// 依赖注入
        /// 构造方法 构造注入（其中一个方法）
        /// 初始化数据库上下文
        /// </summary>
        /// 商品控制器对象 依赖于 Store_2022Context数据库上下文对象
        public CommonalityController(ShopContext db, IDataServices dataService, ISingletonServices singletonServices, ITransientService transientService, IScopedService scopedService)
        {
            //把构造方法里面db赋值给_db
            _db = db;
            _dataService = dataService;
            _singletonServices = singletonServices;
            _transientService = transientService;
            _scopedService = scopedService;

        }
        /// <summary>
        /// 新增商品
        /// </summary>
        [HttpGet]
          public string AddShop(Models.AddShopRequest request)
        {
            //后端业务逻辑  

            //把单个的请求参数  转换成 数据的类
            var shop = new Shop
            {
                Name = request.Name,
                Price = request.Price,
                Jj = request.Jj,
                Number = request.Number,
                ShopZt=request.ShopZt,
                Img=request.Img
            };
            _db.Shops.Add(shop);
            var row = _db.SaveChanges();
            if (row > 0)
                return "新增成功";
            return "新增失败";
        }
        /// <summary>
        /// 新增分类
        /// </summary>
        [HttpGet]
        
        public string AddKind(AddKind2Request request)
        {
            var kind = new Kind()
            {
                Kind1 = request.Kind1
                
            };
            _db.Kinds.Add(kind);
            var row = _db.SaveChanges();
            if (row > 0)
                return "新增成功";
            return "新增失败";
        }
        /// <summary>
        /// 修改商品
        /// </summary>
        [HttpPost]
        public string UpdateShop2(UpdateShop2 request)
        {
            //把需要更新的商品 查询出来
            var Shop = _db.Shops.FirstOrDefault(x => x.ShopId == request.ShopId);
            //空处理
            if (Shop == null)
                return "商品不存在";
            //对商品的字段进行赋值
            Shop.Name = request.Name;
            Shop.ShopId = request.ShopId;
            Shop.Jj = request.Jj;
            Shop.Price = request.Price;
            Shop.Number = request.Number;
            Shop.ShopZt = request.ShopZt;
            Shop.Img = request.Img;

            //更新操作
            //上下文.表名.操作方法
            _db.Shops.Update(Shop);
            //保持更新
            var row = _db.SaveChanges();
            if (row > 0)
                return "修改成功";
            return "修改失败";
        }
        /// <summary>
        /// 更新商品分类
        /// </summary>
       
        [HttpPost]
        public string UpdateKind2(UpdateKind2 request)
        {
            //把需要更新的商品分类 查询出来
            var Kind = _db.Kinds.FirstOrDefault(x => x.KindId == request.KindId);
            //空处理
            if (request == null)
                return "分类不存在";
            //对商品的字段进行赋值
            Kind.Kind1 = request.Kind1;
           
            //更新操作
            //上下文.表名.操作方法
            _db.Kinds.Update(Kind);
            //保持更新
            var row = _db.SaveChanges();
            if (row > 0)
                return "更新成功";
            return "更新失败";
        }
        /// <summary>
        /// 删除商品
        /// </summary>
        [HttpPost]
        public string DeketeShop(int id)
        {
            //删除业务
            var shop = _db.Shops.FirstOrDefault(x => x.ShopId == id);
            //空处理
            if (shop == null)
                return "商品不存在";
            //删除
            //上下文.表名.操作方法
            _db.Shops.Remove(shop);
            //保持更新
            var row = _db.SaveChanges();
            if (row > 0)
                return "删除成功";
            return "删除失败";

        }
        /// <summary>
        /// 删除分类
        /// </summary>
        [HttpGet]
        public string DeketeKind(int id)
        {
            //删除业务
            var kind = _db.Kinds.FirstOrDefault(x => x.KindId == id);
            //空处理
            if (kind == null)
                return "商品不存在";
            //删除
            //上下文.表名.操作方法
            _db.Kinds.Remove(kind);
            //保持更新
            var row = _db.SaveChanges();
            if (row > 0)
                return "删除成功";
            return "删除失败";

        }
        /// <summary>
        /// 查询商品
        /// </summary>
         [HttpPost]
        public List<Shop> GetShops(GetShopsRequest request)
        {
            //关键字
            var shopDb = _db.Shops.AsQueryable();
            //如果输入关键字 则添加这个条件
            if (!string.IsNullOrEmpty(request.Keyword))
                shopDb = shopDb.Where(x => x.Name.Contains(request.Keyword));
            //否则不添加条件

            //分页
            return shopDb
                  .OrderByDescending(x => x.ShopId)
                  //跳过
                  .Skip((request.PageIndex - 1) * request.PageSize)
                  //取多少个
                  .Take(request.PageSize)
                  //ToList()
                  //之前是编辑SQL
                  //之后执行SQL
                  //执行查询语句
                  .ToList();
        }
        
       
        /// <summary>
        /// 查询商品分类
        /// </summary>
        [HttpPost]
        public List<Kind> GetKinds(GetKindsRequest request)
        {
            //待执行命令 正在组建SQL语句
            var kindDB = _db.Kinds.AsQueryable();
            if (!string.IsNullOrEmpty(request.Keyword))
                kindDB = kindDB.Where(x => x.Kind1.Contains(request.Keyword));

            //返回查询结果
            return kindDB
                .OrderByDescending(x => x.KindId)
                .Skip((request.PageIndex - 1) * request.PageSize)
                .Take(request.PageSize)
                .ToList();
        }
        ///前端商品分类接口
                [HttpPost]
        public List<Kind> GetCategoryList()
        {
            var cateList = _db.Kinds.ToList();
            return cateList;
        }

        //前端商品列表接口 输入：商品分类Id,搜索关键字，分页数据 输出：商品列表（商品名称，商品Id，商品图片），总数
        /// <summary>
        /// 前端商品列表接口
        /// </summary>
        /// <param name="reqeust"></param>
        /// <returns></returns>
        [HttpPost]
        public GetShopListResponse GetGoodList(GetShopListRequest reqeust)
        {
            //实现这个接口
            var shopDB = _db.Shops.AsQueryable();

            //如果符合关键字不为空
            if (!string.IsNullOrEmpty(reqeust.Keyword))
                shopDB = shopDB.Where(x => x.Name.Contains(reqeust.Keyword));

           //如果符合分类Id>0
            if (reqeust.ShopId > 0)
                shopDB = shopDB.Where(x => x.ShopId == reqeust.ShopId);
            
            //获取总数
            var total = shopDB.Count();

           var list = shopDB
                //构造新的列表类型
                .Select(x => new ShopModel
                {
                    ShopId = x.ShopId,
                    Img = x.Img,
                    Name=x.Name
                })
                .OrderByDescending(x => x.ShopId)
                .Skip((reqeust.PageIndex - 1) * reqeust.PageSize)
                .Take(reqeust.PageSize)
                .ToList();

            //返回对象
            //自己定义了一个返回类 创建这个返回对象去返回
            var response = new GetShopListResponse
            {
                ShopList = list,
                Total = total
            };
            return response;
        }

        //前端商品详情接口 输入：商品Id 输出：商品标题，图片，价格，库存，描述
        /// <summary>
        /// 前端商品详情接口
        /// </summary>
        /// <param name="goodId"></param>
        /// <returns></returns>
        [HttpPost]
        public GetShopDetailResponse GetShopDetail(int shopId)
        {
            var shop = _db.Shops.FirstOrDefault(x => x.ShopId == shopId);
            if (shop == null)
                return null;

            var repsonse = new GetShopDetailResponse { 
                Img= shop.Img,
                ShopName= shop.Name,
                Jj= shop.Jj,
                Price= shop.Price,
                Number= shop.Number
            };
            return repsonse;
        }












        [HttpPost]
        public string Singleton()
        {

            //这个对象是控制器里面获取的
            //_dataService
            //这个对象是通过方法注入获取的
            //dataService2
            //判断这两个是不是同一个对象 GetHashCode 获取对象的HashCode 不同的对象Hashcode是不一样的 
            return "_singletonServices的hashCode:" + _singletonServices.GetHashCode();
        }
        [HttpPost]
        public string Transient([FromServices] ITransientService transientService2)
        {

            //判断这两个是不是同一个对象 GetHashCode 获取对象的HashCode 不同的对象Hashcode是不一样的 
            return "1的hashCode:" + _transientService.GetHashCode() + "2的hashCode:" + transientService2.GetHashCode();
        }
        /// <summary>
        /// 瞬时的 每次获取都是新的对象
        /// </summary>
        /// <param name="scopedService"></param>
        /// <returns></returns>
        [HttpPost]
        public string Scoped([FromServices] IScopedService scopedService)
        {
            //判断这两个是不是同一个对象 GetHashCode 获取对象的HashCode 不同的对象Hashcode是不一样的 
            return "1的hashCode:" + _scopedService.GetHashCode() + "2的hashCode:" + scopedService.GetHashCode();
        }
        
    }

   
}
